import { Button, message, notification } from 'antd';

import React from 'react';
import { useIntl } from 'umi';
import defaultSettings from '../config/defaultSettings';
import { AUTH_TOKEN } from './utils/request';



if (REACT_APP_ENV == 'local') {
  localStorage.setItem(AUTH_TOKEN, 'eyJ4NXQjUzI1NiI6IlN4cXFkV1l4VDdCWnJkSC11VnBnQUhmWDJxMzRxUHl4eDRvblg2bXYtcUkiLCJqa3UiOiJodHRwOlwvXC9sb2NhbGhvc3Q6ODA4MFwvb2F1dGgyXC9qd2tzIiwia2lkIjoiam9zZSIsInR5cCI6IkpXVCIsImFsZyI6IlJTMjU2In0.eyJzdWIiOiJpcWlkYW8iLCJhdWQiOlsiaHR0cHM6XC9cL2NsaWVudDEuaXFpZGFvLmNvbSIsImh0dHBzOlwvXC9jbGllbnQyLmlxaWRhby5jb20iXSwibmJmIjoxNjU2NjY2ODIzLCJjb2RlIjoiMTY1MDI2ODg2MDY2OCIsImlzcyI6ImlxaWRhbyIsImV4cCI6MTY1NzI3MTY4MywiaWF0IjoxNjU2NjY2ODgzLCJqdGkiOiJhZTk0ZTQ3Zi02NDM4LTRmNTMtOWJmOC02ZTM3Yjg4ZGZiMmYifQ.Bl-ErX_QUOg83drN3Okr5-1xE81n1Xj7NDLRJ2afTn_k-M1feSiS7HZQIWFNHIbUHu4lNM-zrgTt9GeH91OXDElA9Pa91NwbFZSrwqpfdOJE4jWJo-bxCVamjqZfCO1jNgzs_rv0aWre0zDiRw1389u5TXghAyWfGTR3MKzL_VvcbRdLnkcinmhkvt5oMyAgvmEhWWndDuxUj2df34D3UuXd2n2PPOsyCuARaWUtjj5v3eT8gtBJNtq-SziHCTDJsul23yl8Nd-QSAXdaSo0pKB8TuiTsrViHX02O77s-KNVhHFWBOsOZojR8jLOMnl8HwDfmCw-2JEQmcYBc5jg2g')
}
const { pwa } = defaultSettings;
// if pwa is true
if (pwa) {
  // Notify user if offline now
  window.addEventListener('sw.offline', () => {
    message.warning(useIntl().formatMessage({ id: 'app.pwa.offline' }));
  });

  // Pop up a prompt on the page asking the user if they want to use the latest version
  window.addEventListener('sw.updated', (event: Event) => {
    const e = event as CustomEvent;
    const reloadSW = async () => {
      // Check if there is sw whose state is waiting in ServiceWorkerRegistration
      // https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration
      const worker = e.detail && e.detail.waiting;
      if (!worker) {
        return true;
      }
      // Send skip-waiting event to waiting SW with MessageChannel
      await new Promise((resolve, reject) => {
        const channel = new MessageChannel();
        channel.port1.onmessage = (msgEvent) => {
          if (msgEvent.data.error) {
            reject(msgEvent.data.error);
          } else {
            resolve(msgEvent.data);
          }
        };
        worker.postMessage({ type: 'skip-waiting' }, [channel.port2]);
      });
      // Refresh current page to use the updated HTML and other assets after SW has skiped waiting
      window.location.reload(true);
      return true;
    };
    const key = `open${Date.now()}`;
    const btn = (
      <Button
        type="primary"
        onClick={() => {
          notification.close(key);
          reloadSW();
        }}
      >
        {useIntl().formatMessage({ id: 'app.pwa.serviceworker.updated.ok' })}
      </Button>
    );
    notification.open({
      message: useIntl().formatMessage({ id: 'app.pwa.serviceworker.updated' }),
      description: useIntl().formatMessage({ id: 'app.pwa.serviceworker.updated.hint' }),
      btn,
      key,
      onClose: async () => { },
    });
  });
} else if ('serviceWorker' in navigator) {
  // unregister service worker
  const { serviceWorker } = navigator;
  if (serviceWorker.getRegistrations) {
    serviceWorker.getRegistrations().then((sws) => {
      sws.forEach((sw) => {
        sw.unregister();
      });
    });
  }
  serviceWorker.getRegistration().then((sw) => {
    if (sw) sw.unregister();
  });

  // remove all caches
  if (window.caches && window.caches.keys) {
    caches.keys().then((keys) => {
      keys.forEach((key) => {
        caches.delete(key);
      });
    });
  }
}
